package com.example.qzzm;

import java.util.HashMap;
import java.util.Map;
import java.util.Timer;
import java.util.TimerTask;
import java.util.regex.Matcher;
import java.util.regex.Pattern;

import com.example.application.QZApplication;
import com.example.constant.App;
import com.example.net.Client;
import com.example.qzzm.R;

import android.text.Editable;
import android.text.TextUtils;
import android.text.TextWatcher;
import android.view.View;
import android.view.View.OnClickListener;
import android.widget.EditText;
import android.widget.ImageView;
import android.widget.RelativeLayout;
import android.widget.TextView;
import android.widget.Toast;
import android.annotation.SuppressLint;
import android.app.Activity;
import android.content.Intent;
import android.os.AsyncTask;
import android.os.Bundle;
import android.os.Handler;

/**
 * 注册界面的Activity
 * 
 * @author Administrator
 *
 */
public class RegisterActivity extends Activity implements TextWatcher {

	// 登录按钮
	private RelativeLayout rlRegister;
	// 返回按钮
	private ImageView ivBack;

	// 输入框
	private EditText etPhone;
	private EditText etCode;
	private EditText etPwd;
	private TextView getCode;
	private QZApplication application;

	// 协议
	private TextView tvAgreement;
	// 剩余等待时间
	private int leftTime = 0;

	// 处理验证码等待
	@SuppressLint("HandlerLeak")
	Handler Handler = new Handler() {
		@Override
		public void handleMessage(android.os.Message msg) {
			// TODO Auto-generated method stub
			super.handleMessage(msg);

			switch (msg.what) {
			case 0:
				getCode.setText("剩余" + String.valueOf(leftTime) + "秒");
				break;
			case 1:
				getCode.setText("获取验证码");
				break;
			default:
				break;
			}
		}
	};

	@Override
	protected void onCreate(Bundle savedInstanceState) {
		super.onCreate(savedInstanceState);
		setContentView(R.layout.activity_register);
		application = (QZApplication) getApplication();
		initView();
		initListeners();

	}

	// 初始化布局控件
	private void initView() {
		rlRegister = (RelativeLayout) findViewById(R.id.rl_register);
		ivBack = (ImageView) findViewById(R.id.iv_back);
		etPhone = (EditText) findViewById(R.id.et_phone);
		etCode = (EditText) findViewById(R.id.et_code);
		etPwd = (EditText) findViewById(R.id.et_password);
		getCode = (TextView) findViewById(R.id.tv_getcode);

		tvAgreement = (TextView) findViewById(R.id.tv_agreement);
	}

	// 初始化监听事件
	private void initListeners() {
		etPwd.addTextChangedListener(this);
		etPhone.addTextChangedListener(this);

		rlRegister.setOnClickListener(new OnClickListener() {

			@Override
			public void onClick(View v) {
				if (validInput()) {
					// 跳转
					RegTask regTask = new RegTask();
					regTask.execute();
				}
			}
		});

		ivBack.setOnClickListener(new OnClickListener() {

			@Override
			public void onClick(View v) {
				finish();
			}
		});

		getCode.setOnClickListener(new OnClickListener() {

			@Override
			public void onClick(View v) {
				if (leftTime > 0) {
					return;
				}
				String phone = "";
				if (valPhone(phone = etPhone.getText().toString().trim())) {
					FirstTask firstTask = new FirstTask();
					firstTask.execute(phone);

					TimerTask timerTask = new TimerTask() {

						@Override
						public void run() {
							if (leftTime <= 0) {
								Handler.sendEmptyMessage(1);
								this.cancel();
							}
							leftTime--;
							Handler.sendEmptyMessage(0);
						}
					};
					leftTime = 60;
					Timer timer = new Timer();
					timer.schedule(timerTask, 0, 1000);
				} else {
					etPhone.setError("手机格式不正确");
				}
			}
		});

		tvAgreement.setOnClickListener(new OnClickListener() {

			@Override
			public void onClick(View v) {
				startActivity(new Intent(RegisterActivity.this,
						AgreeActivity.class));
			}
		});
	}

	// 过滤输入的数据
	private boolean validInput() {
		if (TextUtils.isEmpty(etPhone.getText().toString().trim())) {
			etPhone.setError("不能为空");
			return false;
		}
		if (TextUtils.isEmpty(etCode.getText().toString().trim())) {
			etPhone.setError("不能为空");
			return false;
		}
		if (TextUtils.isEmpty(etPwd.getText().toString().trim())) {
			etPhone.setError("不能为空");
			return false;
		}
		if (etPwd.getText().toString().trim().length() < 6) {
			etPhone.setError("密码太短(建议6-12)");
			return false;
		}
		if (etPwd.getText().toString().trim().equals("")) {
			etPhone.setError("验证码错误");
			return false;
		}
		return true;
	}

	// 过滤手机号
	private boolean valPhone(String ph) {
		String regString = "1[358]([0-9]{9})";
		Pattern pattern = Pattern.compile(regString);
		Matcher matcher = pattern.matcher(ph);
		if (matcher.find()) {
			return true;
		} else {
			return false;
		}
	}

	class FirstTask extends AsyncTask<String, String, String> {

		@Override
		protected String doInBackground(String... params) {
			// 开始执行
			// 网络访问，获取列表数据
			Client client = application.getClient();
			String result = client.getResquest(App.CODE_URL + params[0]);
			return result;
		}

		@Override
		protected void onPostExecute(String result) {
			Toast.makeText(RegisterActivity.this, result, Toast.LENGTH_LONG)
					.show();

			super.onPostExecute(result);
		}

		@Override
		protected void onProgressUpdate(String... values) {
			// 更新
			super.onProgressUpdate(values);
		}
	}

	class RegTask extends AsyncTask<String, String, String> {

		@Override
		protected String doInBackground(String... params) {
			// 开始执行
			Map<String, String> dataMap = new HashMap<String, String>();
			dataMap.put("phone", etPhone.getText().toString().trim());
			dataMap.put("code", etCode.getText().toString().trim());
			dataMap.put("password", etPwd.getText().toString().trim());
			dataMap.put("need_code", "1");
			dataMap.put("c_name", application.getCity());
			dataMap.put("lon", "30.1");
			dataMap.put("lat", "121.0");
			// 网络访问，获取列表数据
			Client client = application.getClient();
			String result = client.postResquest(App.REGISTER_URL, dataMap);
			if (result != null) {
				System.out.println(result);
			}
			return result;
		}

		@Override
		protected void onPostExecute(String result) {
			Toast.makeText(RegisterActivity.this, result, Toast.LENGTH_LONG)
					.show();
			super.onPostExecute(result);
		}

		@Override
		protected void onProgressUpdate(String... values) {
			// 更新
			super.onProgressUpdate(values);
		}
	}

	@Override
	public void afterTextChanged(Editable s) {
		// TODO Auto-generated method stub

	}

	@Override
	public void beforeTextChanged(CharSequence s, int start, int count,
			int after) {
		// TODO Auto-generated method stub

	}

	@Override
	public void onTextChanged(CharSequence s, int start, int before, int count) {
		if (!TextUtils.isEmpty(etPhone.getText().toString().trim())
				&& !TextUtils.isEmpty(etPwd.getText().toString().trim())) {
			rlRegister
					.setBackgroundResource(R.drawable.selector_ly_loginbutton);
		} else {
			rlRegister.setBackgroundResource(R.drawable.corner_button_unnormal);
		}
	}
}
